var util = require('./utils/util.js');
var api = require('./config/api.js');
var user = require('./services/user.js');
var that;
App({
  onLaunch: function(options) {
    that = this;
    that._initData(options);
    that.update();
  },
  update(){
    // 获取小程序更新机制兼容    
    if (wx.canIUse('getUpdateManager')) {    
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
          // 请求完新版本信息的回调        
          if (res.hasUpdate) {
            updateManager.onUpdateReady(function () {    
              wx.showModal({
                title: '更新提示',    
                content: '新版本已经准备好，是否重启应用？',          
                success: function (res) {     
                  if (res.confirm) {      
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                      updateManager.applyUpdate()     
                  } 
                } 
              })
            })
            updateManager.onUpdateFailed(function () {
              //新的版本下载失败
              wx.showModal({
                title: '已经有新版本了哟~',
                content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
              })
            })
          }
      })    
    } else {      
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示      
      wx.showModal({        
        title: '提示',        
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'      
      })    
    }
  },
  _initData(options){
    that.wxReqs = util.wxReq.plugin();
    that.wxReq = that.wxReqs[0];
    that.wxPureReq = that.wxReqs[1];
    that.getBaseEnums();
    //判断游客
    if (wx.getStorageSync('isTouristRent')) {
      that.isTouristRent = wx.getStorageSync('isTouristRent');
    } else {
      wx.setStorageSync('isTouristRent', that.isTouristRent);
    }
    //实名认证是否成功
    if (wx.getStorageSync('isCert')) {
      that.globalData.isCert = wx.getStorageSync('isCert');
    } else {
      wx.setStorageSync('isCert', that.globalData.isCert);
    }
    //获取用户的登录信息
    if (wx.getStorageSync('phoneNumber') && wx.getStorageSync('token')) {
      if (wx.getStorageSync("isAuthBaseInfo")) {
        that.globalData.isAuthBaseInfo = true;
        that.globalData.userInfo = wx.getStorageSync("userInfo");
      }
      that.globalData.phoneNumber = wx.getStorageSync("phoneNumber");
      that.globalData.tenantNo = wx.getStorageSync("tenantNo");
      that.globalData.hasLogin = true;
    } else {
      that.globalData.hasLogin = false;
      if (options.scene) { } else {
        wx.redirectTo({
          url: '/pages/auth/login/autoLogin',
        })
      }
    } 
  },
  getBaseEnums(){
    //初始化数据配置
    return new Promise(function (resolve, reject) {
      if (!util.isNullOrEmpty(wx.getStorageSync("baseEnums"))) {
        that.baseEnums = wx.getStorageSync("baseEnums");
        that.fsurl = that.baseEnums.fileServerUrl;
        resolve(that.baseEnums);
      } else {
        that.post(api.GetBaseInfoLs, { retry: 3, isAllow: true}).then(rsp => {
          if (rsp.data) {
            that.baseEnums = rsp.data;
            wx.setStorageSync("baseEnums", rsp.data);
            that.fsurl = rsp.data.fileServerUrl;
            resolve(that.baseEnums);
          }
        }).catch((err) => {
          reject(false);
        });
      }
    });
  },
  upload(file, url = api.StorageUpload, fileName = 'imgfile') {
    return util.upload.single(file, fileName, url).catch((res)=>{
      if (res.data.errno == 401) {
        var msg = "请先登录后操作!";
        if (wx.getStorageSync('phoneNumber') && wx.getStorageSync('token')) {
          msg = "登录状态失效,请重新登录！";
        }
        //需要登录后才可以操作
        util.confirm.openExt(msg, function () {
          wx.clearStorage();
          that.globalData.hasLogin = false;
          var p = encodeURIComponent(util.getCurrentPageUrlWithArgs());
          wx.redirectTo({
            url: '/pages/auth/login/autoLogin?page=' + p,
          })
        });
      }
      return Promise.reject(res);
    });
  },
  uploads(files, url = api.StorageUpload, fileName = 'imgfile') {
    return util.upload.mutiles(files, fileName, url);
  },
  delAuthFile(fp) { //删除文件
    if (fp && fp.indexOf('/') != -1) {
      if (fp.indexOf('http:') != -1) {
        fp = that.realFp(fp);
      }
      return that.postPureForm(api.delInfoAuthUpload, { fp: fp }).then(rsp => {
        return Promise.resolve(rsp.data);
      }).catch((err) => {
        return Promise.reject(false);
      });
    }
  },
  removeFiles(fps, url = api.RemoveUpload, arr = []) { //删除文件
    return new Promise(function (resolve, reject) {
      if (fps.length > 0) {
        that.removeFile(fps[0], url).then(rsp => {
          arr.push(rsp);
          if (fps.length > 1) {
            that.removeFiles(fps.slice(1), url, arr).then(rsp => {
              resolve(rsp);
            }).catch((err) => {
              reject(err);
            });
          } else {
            resolve(arr);
          }
        }).catch((err) => {
          reject(err);
        });
      } else {
        resolve(arr);
      }
    });
  },
  removeFile(fp, url = api.RemoveUpload) { //删除文件
    if (fp && fp.indexOf('/') != -1) {
      if (fp.indexOf('http:') != -1) {
        fp = that.realFp(fp);
      }
      return that.postPureForm(url, { fp: fp, isAllow:true }).then(rsp => {
        return Promise.resolve(rsp.data);
      }).catch((err) => {
        return Promise.reject(false);
      });
    }
  },
  realFp(fp) {
    if (fp && fp.indexOf('oss') != -1) {
      return fp;
    }
    return fp.replace(that.fsurl, '');
  },
  showImg(fp) { //显示图片
    if(fp && fp.indexOf('oss') != -1){
      return fp;
    }
    return that.fsurl + fp;
  },
  loadPagePost: function (url, page, params = {}) {
    return that.loadPageExt(url, page, params, 'post');
  },
  loadPageExt: function (url, page, params = {}, method = 'postForm') {
    return new Promise(function (resolve, reject) {
      var q = {};
      var load = function () {
        Object.assign(q, page.config, params);
        return that[method](url, q, { retry: 3 }).then(rsp => {
          let res = rsp.data;
          if (res.list) {
            let pd = res.list; //每页数据
            if (page.isLoad(pd)) {
              page.next();
            }
            return Promise.resolve(pd);
          } else {
            if (page.isLoad(res)) {
              page.next();
            }
            return Promise.resolve(res);
          }
        }).catch((err) => {
          return Promise.reject(err);
        });
      }
      if (page.hasLoad) {
        return load().then(rsp => {
          resolve(rsp);
        }).catch((err) => {
          reject(err);
        });
      } else {
        resolve([]);
      }
    });
  },
  loadPageForm: function (url, params, bindData, $scope, page) {
    var q = {};
    var load = function () {
      Object.assign(q, page.config, params);
      that.postForm(url, q, { retry: 3 }).then(rsp => {
        let res = rsp.data;
        let pd = res.list; //每页数据
        pd.forEach(function (item, index) {
          $scope.data[bindData].push(item);
        });
        var temp = {};
        temp[bindData] = $scope.data[bindData];
        $scope.setData(temp);
        if (page.isLoad(pd)) {
          page.next();
        }
      }).catch((err) => {
        console.log('err', err);
      });
    }
    if (page.hasLoad) {
      load();
    }
  },
  loadPage: function (url, params, bindData, $scope, page) {
    var q = {};
    var load = function () {
      Object.assign(q, page.config, params);
      that.post(url, q, {retry:3}).then(rsp => {
        let res = rsp.data;
        let pd = res.list; //每页数据
        pd.forEach(function (item, index) {
          $scope[bindData].push(item);
        });
        var temp = {};
        temp[bindData] = $scope[bindData];
        $scope.setData(temp);
        if (page.isLoad(pd)) {
          page.next();
        }
      }).catch((err) => {
        console.log('err', err);
      });
      if (page.hasLoad) {
        load();
      }
    }
  },
  wxReq: Object,
  wxPureReq: Object,
  postPureForm: function (url, data = {}, config = {}) {
    config['Content-Type'] = 'application/x-www-form-urlencoded';
    return that.postPure(url, data, config);
  },
  postForm: function (url, data = {}, config = {}) {
    config['Content-Type'] = 'application/x-www-form-urlencoded';
    return that.post(url, data, config);
  },
  getPureForm: function (url, data = {}, config = {}) {
    config['Content-Type'] = 'application/x-www-form-urlencoded';
    return that.getPureQ(url, data, config);
  },
  getForm: function (url, data = {}, config = {}) {
    config['Content-Type'] = 'application/x-www-form-urlencoded';
    return that.getQ(url, data, config);
  },
  postPure: function (url, data = {}, config = {}) {
    return that.getPureQ(url, data, config, "POST");
  },
  post: function (url, data = {}, config = {}) {
    return that.getQ(url, data, config, "POST");
  },
  getPureQ: function (url, data = {}, config, method = "GET") {
    return that.getCommon(url, data, config, method, that.wxPureReq);
  },
  getQ: function (url, data = {}, config, method = "GET") {
    return that.getCommon(url, data, config, method).then((rsp) => {
      wx.hideToast();
      wx.hideLoading();
      return Promise.resolve(rsp);
    });
  },
  getCommon: function (url, data = {}, config, method = "GET", wxReq = that.wxReq) {
    /*if (!that.globalData.hasLogin && !data.isAllow){
      wx.redirectTo({
        url: '/pages/auth/login/login',
      })
      return Promise.reject(false);
    }else{
      delete data['isAllow'];
    }*/
    if (!that.isTouristRent && !data.isAllow) {
      util.confirm.modal('您还未办理入住或房东还未为您系统登记,请您尽快与房东联系', '温馨提示',function(){
        if (!that.globalData.hasLogin) {
          wx.navigateTo({
            url: '/pages/auth/login/autoLogin',
          })
        }else{
          let p = getCurrentPages();
          if (p.length > 1) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      });
      return Promise.reject(false);
    } else {
      delete data['isAllow'];
    }
    let header = {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'X-Rent-Token': wx.getStorageSync('token')
    };
    if (config['Content-Type']) {
      header['Content-Type'] = config['Content-Type'];
      delete config['Content-Type'];
    }

    var retry = 0; //允许请求失败次数
    if (config['retry']) {
      retry = config['retry'];
      delete config['retry'];
    }
    config.header = header;
    let opt = Object.assign({}, { data: data, method: method }, config);

    if (opt.data.retry) {
      retry = opt.data.retry;
      delete opt.data['retry'];
    }
    var req = function () {
      return wxReq.request(url, opt).then(res => {
        retry = 0;
        if (res.data.errno == 401) {
          var msg = "请先登录后操作!";
          if (wx.getStorageSync('phoneNumber') && wx.getStorageSync('token')) {
            msg = "登录状态失效,请重新登录！";
          }
          //需要登录后才可以操作
          util.confirm.openExt(msg, function () {
            wx.clearStorage();
            that.globalData.hasLogin = false;
            var p = encodeURIComponent(util.getCurrentPageUrlWithArgs());
            wx.redirectTo({
              url: '/pages/auth/login/autoLogin?page=' + p,
            })
          });
          return Promise.reject(res.data);
        } else if (res.data.errno == 0) {
          return Promise.resolve(res.data);
        } else {
          console.log("resxxxxx", res);
          wx.hideToast();
          wx.hideLoading();
          if (res.data.errno == 1) {
            util.confirm.modal(res.data.errmsg + "(" + JSON.stringify(res.data.data) + ")");
            return Promise.reject(res.data);
          } else {
            if (res.data.errmsg && res.data.errmsg.length < 7) {
              util.toast.fail(res.data.errmsg);
            } else {
              util.confirm.modal(res.data.errmsg);
            }
            return Promise.reject(res.data);
          }
        }
      }).catch((err) => {
        if (err.errMsg == "request:fail timeout") {
          if (retry > 0) {
            retry--;
            return req();
          } else {
            util.toast.fail("请求超时！");
          }
        }
        return Promise.reject(err);
      });
    }
    return req();
  },
  onPageNotFound(res) {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  isExit:false,
  fsurl: '',
  /**
   * noticeTypes 通知类型
   * roomTypes 房间类型
   * deviceLs 设备
   */
  baseEnums: {},
  isTouristRent:false, //默认没有出租
  relevanceA:{ //小程序A跳转参数
    appId: '',
    path: '',
    envVersion: '',
  },
  globalData: {
    userInfo: {
      nickName: '点击登录',
      userName: '点击登录',
      avatarUrl: ''
    },
    appName:'9580租客',
    hasLogin: false,
    phoneNumber:'',
    tenantNo:'', //租客编号
    isCert:false, //是否实名认证
    isAuthBaseInfo: false,
    ownersNo: '' //D1000450780265,D1002911859582
  }
})